<template>
  <div class="upTemplate">
    <div class="preview">
      <div v-for="(item, index) in fileLists" :key="index">
        <div class="upImg" v-if="!item.videoSrc">
          <img :src="item.imageSrc" alt="image" @click="previewImg(item.imageSrc, index)">
          <van-icon name="close" class="iconColse" @click="closeImg(index)"/>
        </div>
        <div class="upImg" v-else>
          <!-- poster是video标签封面属性 -->
          <video v-if="!isUseImg" :src="item.videoSrc" @click="playvides(item.videoSrc)" poster="./logo.png"></video>
          <img v-else
           :src="item.imageSrc" alt="video" @click="playvides(item.videoSrc)"/>
          <van-icon name="close" class="iconColse" @click="closeImg(index)"/>
        </div>
      </div>
      <div class="el-upload" v-if="isDone && fileLists">
        <van-loading type="spinner" color="#1989fa" /> 
      </div>  
    </div>
    <div>
      <van-uploader :before-read="beforeRead" :after-read="afterRead" accept="*">
        <van-button icon="plus" type="primary">上传文件</van-button>
      </van-uploader>
    </div>
    <div id="output">
      <img :src="vdeImg" alt="" srcset="">
    </div> 
    <!-- <video :src="videorc1"></video> -->
  </div>
</template>

<script>
// import axios from 'axios'
import Vue from 'vue'
import { Toast, ImagePreview, Icon, Loading } from 'vant';
Vue.use(Toast)
Vue.use(ImagePreview )
Vue.use(Loading)
Vue.use(Icon)
export default {
  data() {
    return {
      fileLists: [], //预览文件
      uploadUrl: '', //上传的地址
      onCompress: false, //是否开启图片压缩
      isDone: false, //图片加载完成,true开始加载，false完成
      imgrc: 'http://ddwl.file.qiankunhaoche.com/d50f9123-deb9-c703-14dd-df45a2816bc5.png',
      imgrc1: 'https://sjwl-qnc.oss-cn-beijing.aliyuncs.com/1597387382035u=19064698564113625838&fm=26&gp=0.jpg.png',
      videorc: 'https://sjwl-qnc.oss-cn-beijing.aliyuncs.com/15973139012256f05b6e3872681d2a50239c70e92d0ff.mp4.mp4',
      videorc1: 'http://192.168.0.104:4000/images/002.mp4',
      vdeImg: '',
      needUpData: [], //需要上传的数据
      iphone: false,
      isUseImg: true, //是否使用图片显示video缩略图
    }
  },
  created() {
    this.isIphone()
  },
  methods: {
    //上传前置处理
    beforeRead(file) {
      console.log(file)
      let type = file.type
      //只能上传图片或视频
      if(this.isImage(type) || this.isVideo(type)) {
        this.isDone = true
        return true
      } else {
        Toast('只能上传图片或视频')
        return false
      }
      
    },
    //上传完成回调
    afterRead(file) {
      console.log(file)
      let that = this
      // 请求接口
      setTimeout(() => {
        that.isDone = false
        if(that.isVideo(file.file.type)) {     
          if(!that.isUseImg) {
            //1. 使用video标签直接显示，回显速度快。
            that.fileLists.push({imageSrc: that.imgrc1, videoSrc: that.videorc1 })
          }else {
            //2. 使用img标签，显示视频的某一帧画面，处理成图片，速度慢一些。
            that.getVideoBase64(that.videorc1).then(res => {
              that.fileLists.push({imageSrc: res, videoSrc: that.videorc1 })
            })
          }  
        } else {
          that.fileLists.push({imageSrc: that.imgrc}) 
        }
        
      }, 800)
    },
    //判断是否图片
    isImage(type) {
      return [
        "image/jpeg",
        "image/png",
        "image/jpg",
        "image/gif",
        "image/bmp"
      ].includes(type);
    },
    //判断是否视频
    isVideo(type) {
      return [
        "video/mp4",
        "video/ogg",
        "video/flv",
        "video/avi",
        "video/wmv",
        "video/rmvb",
        "video/mov",
        "video/quicktime"
      ].includes(type);
    },
    //删除预览图
    closeImg(index) {
      this.fileLists.splice(index, 1)
      // 同时删除上传数据
      this.needUpData.splice(index, 1) 
    },
    //预览大图
    previewImg(url, index) {
      //先判断是否有视频
      let isAllImg = this.fileLists.some(item => {
        if(item.videoSrc) return true;
      })
      console.log(isAllImg)
      if(!isAllImg) {
        let arrs = []
        this.fileLists.forEach(item => {
          arrs.push(item.imageSrc)
        })
        ImagePreview({
          images: arrs,
          startPosition: index //图片起始位置
        });
      } else {
        ImagePreview([url]);
      }
    },
    //将视频第一帧作为回显缩略图
    getVideoBase64(url) {
      console.log(url, 'url')
      return new Promise(function (resolve, reject) {
          let dataURL = '';
          let video = document.createElement("video");
          video.setAttribute('crossOrigin', 'anonymous');//处理跨域
          video.setAttribute('src', url);
          video.setAttribute('width', 400);
          video.setAttribute('height', 240);
          //如果不设置currentTime，画出来的图片是空的,表示第几帧
          video.currentTime = 300;
          video.addEventListener('loadeddata', function () {
              let canvas = document.createElement("canvas"),
              width = video.width, //canvas的尺寸和图片一样
              height = video.height;
              canvas.width = width;
              canvas.height = height;
              canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
              dataURL = canvas.toDataURL('image/jpeg'); //转换为base64
              console.log(dataURL)
              resolve(dataURL);
          });
      })
    },
    playvides(newUrl){
      // 视频预览组件
      this.$videoPreview(newUrl)
      // H5原生预览视频
      // window.callLocalApp({
      //   func: "playVideo",
      //   params: newUrl
      // });
    },
    isIphone() {
      var u = navigator.userAgent;
      if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {//安卓手机
      alert("安卓手机");
      // window.location.href = "mobile/index.html";
      } else if (u.indexOf('iPhone') > -1) {//苹果手机
      // window.location.href = "mobile/index.html";
      alert("苹果手机");
      } else if (u.indexOf('Windows Phone') > -1) {//winphone手机
      alert("winphone手机");
      // window.location.href = "mobile/index.html";
      }
    }
  }
}
</script>

<style lang="less" scoped>
.upTemplate {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.preview {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .upImg{
    padding: 0 8px 0 0;
    position: relative;
    .iconColse{
      position: absolute;
      top: -10px;
      right: 0;
      z-index: 2;
      font-size: 24px;
      color: black;
    }
    .iphone{
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: red;
    }
    video {
      width: 75px;
      height: 75px;
      object-fit: inherit;
    }
  }
  img {
    width: 75px;
    height: 75px;
    border-radius: 10px;
    object-fit: inherit;
  }
}
.el-upload {
  margin: 0 10px 0 0;
  width: 75px;
  height: 75px;
  border-radius: 10px;
  border: 1px dashed #909399;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>